package communicationModule;

import generalObjects.GroupView;

import java.io.Serializable;
import java.util.Map;
import java.util.Random;

/**
 * Constitutes a general message in the GCom model. The type of message is
 * decided by its header variable. The model uses these objects to transmit and
 * receive messages between participants of a group.
 * 
 */
public class MessageObject implements Serializable {

    private static final long serialVersionUID = -4072088596891793346L;

    private final String header;
    private final GroupView gView;
    private final String data;
    private final String sender;
    private final String sysData;
    private final long id;

    public MessageObject(final String sender, final String header,
            final String data, final GroupView gView, final String sysData) {
        this.sender = sender;
        this.header = header;
        this.data = data;
        this.sysData = sysData;
        this.gView = gView;
        id = Long.parseLong(new Random().nextInt(99999) + ""
                + System.currentTimeMillis());
    }

    public long getId() {
        return id;
    }

    public String getSender() {
        return sender;
    }

    public String getHeader() {
        return header;
    }

    public String getContent() {
        return data;
    }

    public String getSystemData() {
        return sysData;
    }

    public GroupView getGroupView() {
        return gView;
    }

    @Override
    public boolean equals(final Object other) {

        return id == ((MessageObject) other).getId();
    }

    @Override
    public String toString() {

        if (header.equals("message")) {

            final StringBuffer strB = new StringBuffer();
            strB.append("{");
            for (final Map.Entry<String, Integer> entry : gView
                    .getVectorClock().entrySet()) {
                strB.append('"' + entry.getKey() + '"' + ':' + entry.getValue()
                        + ",");
            }
            strB.deleteCharAt(strB.length() - 1);
            strB.append("}");

            return "{ header= " + header + " ; sender= " + sender
                    + " ; vector clock= " + strB.toString() + " ; payload= "
                    + data + " ; id= " + id + " }";
        }
        return "{ header= " + header + " ; sender= " + sender + " ; payload= "
                + data + " ; id= " + id + " }";
    }
}
